package com.coo.font
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	
	/**
	 * 
	 * @ author iCoo
	 * @ 2009.12.07 update
	 * 
	 * @ 사용법
	 * @ 1. font를 담고 있는 swf생성 ( 라이브러리에 Class Name 설정 )
	 * @ 2. ex )
	 * 					var someEmbedFont: EmbedFont = new EmbedFont();
	 * 
	 * 					someEmbedFont.addEventListener( Event.COMPLETE, onComplete );
	 * 					someEmbedFont.load( "./fontAsset/AvantGarde.swf", "AvantGarde" );	// 하나의 url에 반드시 하나의 linkage만 연결된다.
	 * 					
	 * 					private function onComplete( e: Event ): void
	 * 					{
	 * 						trace( someEmbedFont.name );
	 * 					}
	 * 
	 */	
	public class EmbedFont extends EventDispatcher
	{
		protected var fontAsset: FontAsset;
		
		public function EmbedFont(){}
		
		public function load( url: String, linkage: String ): void
		{
			if( fontAsset == null )
			{
				fontAsset = FontAssetManager.getInstance().getFontAsset( url, linkage );
				
				if( fontAsset.isComplete )
				{
					dispatchEvent( new Event( Event.COMPLETE ));
					
				} else if( fontAsset.isError ) {
					dispatchEvent( new Event( IOErrorEvent.IO_ERROR ));
					
				} else {
					fontAsset.addEventListener( Event.COMPLETE, onEvent );
					fontAsset.addEventListener( Event.OPEN, onEvent );
					fontAsset.addEventListener( IOErrorEvent.IO_ERROR, onEvent );
					fontAsset.addEventListener( HTTPStatusEvent.HTTP_STATUS, onEvent );
					fontAsset.addEventListener( ProgressEvent.PROGRESS, onEvent );
				}
			}
			
		}
		
		public function get name(): String
		{
			return fontAsset ? fontAsset.name : null;
		}
		
		public function close(): void
		{
			dispose();
			fontAsset = null;
		}
		
		protected function dispose():void {
			if (fontAsset) {
				fontAsset.removeEventListener(Event.OPEN, onEvent);
				fontAsset.removeEventListener(Event.COMPLETE, onEvent);
				fontAsset.removeEventListener(IOErrorEvent.IO_ERROR, onEvent);
				fontAsset.removeEventListener(ProgressEvent.PROGRESS, onEvent);
				fontAsset.removeEventListener(HTTPStatusEvent.HTTP_STATUS, onEvent);
				fontAsset.close();
			}
		}
		
		protected function onEvent( e: Event ): void
		{
			if( e.type == Event.COMPLETE || e.type == IOErrorEvent.IO_ERROR )
			{
				dispose();
			}
			
			dispatchEvent( e );
		}
	}
}